//
//  NearShopController.m
//  CP20180523
//
//  Created by l wb on 2018/5/25.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "NearShopController.h"
#import "MapKit/MapKit.h"
#import <CoreLocation/CoreLocation.h>
@interface NearShopController ()<MKMapViewDelegate,CLLocationManagerDelegate>
@property (strong, nonatomic) MKMapView *mapView;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, assign) CLLocationCoordinate2D coords;
@property (nonatomic, strong) MKLocalSearchRequest *localSearchRequest;
@property (nonatomic, strong) MKLocalSearch *localSearch;
@end

@implementation NearShopController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"附近彩店";
    
    //调用创建地图视图的方法
    
    [self createMapView];
    // 判断定位操作是否被允许
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        _locationManager  = [CLLocationManager new];
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.delegate = self;
    }
    // 开始定位
    [self.locationManager startUpdatingLocation];
    
    
    
}
#pragma mark -CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [_locationManager stopUpdatingLocation];
    
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray* _Nullable placemarks, NSError * _Nullable error) {
        
        if(error)
            
        {
            
            NSLog(@"查询失败");
            
        } else if(placemarks && placemarks.count > 0)
            
        {
            
            [self issueLocalSearchLookup:@"彩票销售店" usingPlacemarksArray:placemarks];
            
        }
        
    }];
    
   
    
  
}
-(void)issueLocalSearchLookup:(NSString *)searchString usingPlacemarksArray:(NSArray *)placemarks {
    
    // Search 0.250km from point for stores.
    
    CLPlacemark *placemark = placemarks[0];
    
    CLLocation *location = placemark.location;
    
    self.coords = location.coordinate;
    
    // Set the size (local/span) of the region (address, w/e) we want to get search results for.
    
    MKCoordinateSpan span = MKCoordinateSpanMake(0.6250, 0.6250);
    
    MKCoordinateRegion region = MKCoordinateRegionMake(self.coords, span);
    
    [self.mapView setRegion:region animated:NO];
    
    // Create the search request
    
    self.localSearchRequest = [[MKLocalSearchRequest alloc] init];
    
    self.localSearchRequest.region = region;
    
    self.localSearchRequest.naturalLanguageQuery = searchString;
    
    // Perform the search request...
    
    self.localSearch = [[MKLocalSearch alloc] initWithRequest:self.localSearchRequest];
    
    [self.localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
        
        if(error){
            
            NSLog(@"查询无结果");
            
            return;
            
        } else {
            
            // We are here because we have data!  Yay..  a whole 10 records of it too *flex*
            
            // Do whatever with it here...
            
            for(MKMapItem *mapItem in response.mapItems){
                
                // Show pins, pix, w/e...
                
//                NSLog(@"Name for result: = %@", mapItem.placemark.coordinate);
                
                
                
                MKPointAnnotation *annotation0 = [[MKPointAnnotation alloc] init];
                [annotation0 setCoordinate:mapItem.placemark.coordinate];
                [annotation0 setTitle:mapItem.placemark.name];
                [annotation0 setSubtitle:mapItem.placemark.thoroughfare];
                [self.mapView addAnnotation:annotation0];
            
                
            }
            
            [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate];
             MKCoordinateSpan span = MKCoordinateSpanMake(0.02, 0.02);
            MKCoordinateRegion region = MKCoordinateRegionMake(self.mapView.userLocation.location.coordinate, span);
            [self.mapView setRegion:region animated:NO];
            [self.mapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading animated:YES];
            self.mapView.showsUserLocation = YES;
        }
        
    }];
    
}



//创建地图视图的方法
- (void)createMapView {
        //创建地图对象
        _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
         //设置map的类型 或地图模式
        _mapView.mapType = MKMapTypeStandard;
         /*
           8      MKMapTypeStandard = 0, 纸张地图 标准地图
           9      MKMapTypeSatellite,    纯卫星地图
           10      MKMapTypeHybrid,       混合式地图 描述的卫星图
           11      */
         //设置map的初始位置
         //创建地理坐标2D 需要经度和纬度 如：经度：120.366486 纬度：36.083743
         CLLocationCoordinate2D location = CLLocationCoordinate2DMake(36.083743, 120.366486);
         //起始时 锁定一个矩形为1000 X 1000米的方位 ，坐标点location
         _mapView.region = MKCoordinateRegionMakeWithDistance(location, 1000, 1000);
         //设置地图能否放大缩小
         _mapView.zoomEnabled = YES;
         //设置地图能否滚动
         _mapView.scrollEnabled = YES;
         //设置显示用户的位置  先判断是否开始了定位服务
         if ([CLLocationManager locationServicesEnabled] == YES) {
                 //显示用户的位置
                 _mapView.showsUserLocation = YES;
                 //设置用户的基本跟踪状态
                 [_mapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading animated:YES];
        
                 /*
                    29          MKUserTrackingModeNone = 0,        不尾随 一般不设
                    30          MKUserTrackingModeFollow,      尾随用户位置，地图保存正向（北方向）
                    31          MKUserTrackingModeFollowWithHeading 随着地图旋转而尾随（地图方向和设备方向同步）
                    32          */
             }
         //设置代理 需遵守MKMapViewDelegate代理协议
         _mapView.delegate = self;
         //将地图加入到self.view上
         [self.view addSubview:_mapView];
     }




@end
